package product

import (
	"net/http"

	"chain_bridge_service/internal/code"
	"chain_bridge_service/internal/pkg/core"
)

type listRequest struct {
	PageIndex uint `form:"pageIndex"` // 第几页
	PageSize  uint `form:"pageSize"`  // 每页显示条数
}

type Page struct {
	Total int64       `json:"total"`
	List  interface{} `json:"list"`
}

func (h *handler) List() core.HandlerFunc {
	return func(ctx core.Context) {
		req := new(listRequest)
		res := new(createResponse)

		if err := ctx.ShouldBindQuery(&req); err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.ParamBindError,
				code.Text(code.ParamBindError)).WithError(err),
			)
			return
		}

		productList, err := h.productService.List(ctx, req.PageIndex, req.PageSize)
		if err != nil {
			ctx.AbortWithError(core.Error(
				http.StatusOK,
				code.GetProductListError,
				code.Text(code.GetProductListError)).WithError(err),
			)
			return
		}

		count, err := h.productService.Count(ctx)

		page := new(Page)
		page.Total = count
		page.List = productList

		res.Code = code.StatusOK
		res.Data = page
		res.Msg = code.Text(code.StatusOK)
		ctx.Payload(res)
	}
}
